//
//  StwxTableViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/23.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "StwxTableViewModel.h"

#import "ArticleInfoData.h"
#import "ArticlesListData.h"
#import "CommonStwxItemViewModel.h"

@interface StwxTableViewModel()

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;
@property (nonatomic, readwrite, strong) RACCommand* requestDetailCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;

@end

@implementation StwxTableViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = YES;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = NO;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = NO;
    
    /// 请求数据
    self.requestDataCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id inputInfo) {
        
        @strongify(self);
        
        NSInteger loadIndex = [inputInfo[@"LoadIndex"] integerValue];
        
        return [self requestListDataSignalWithPageIndex:loadIndex pageSize:2];
    }];
    
    /// 选中
    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(CommonStwxItemViewModel * itemViewModel) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
                [subscriber sendNext:itemViewModel];
                [subscriber sendCompleted];
            });
            return nil;
        }];
    }];
    // 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    self.requestDetailCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        return [self _requestDetailSignal:input];
    }];
}

- (RACSignal *)_requestDetailSignal:(NSString*)articleID
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    NSString* userID = HCStrValid(um.userData.userID);

    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_articledetail params:interface_param_articledetail(articleID, userID)] subscribeNext:^(id x)
                 {
                     ArticleInfoData* data = [ArticleInfoData modelWithJSON:x];
                     
                     StwxDetailItemViewModel* ivm = [[StwxDetailItemViewModel alloc] initWithData:data cellHeight:self.cellHeight];
                     
                     [subscriber sendNext:ivm];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"请求详情失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal *)requestListDataSignalWithPageIndex:(int)pageIndex pageSize:(int)pageSize
{
    @weakify(self)
    
    BOOL isMyStwx = (self.userID && [self.userID isNotBlank]);
    
    NSString* areaID = HCStrValid(self.areaID);
    
    NSString* strUrl = isMyStwx ? url_interface_mystwx : url_interface_getcatelist;
    NSDictionary* postData = isMyStwx ? interface_param_mystwx(self.userID, @(pageIndex+1), @(pageSize)) : interface_param_getcatelist(@"59", areaID, @(pageIndex+1), @(pageSize));
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        @weakify(self);
        [[AFNetWorkUtils racPOSTWthURL:strUrl params:postData] subscribeNext:^(id x)
        {
            @strongify(self);
            
            ArticlesListData* data = nil;
            
            data = [ArticlesListData modelWithJSON:x];
            
//            if (isMyStwx)
//            {
//                data = [ArticlesListData modelWithJSON:x];
//            }
//            else
//            {
//                data = [ArticlesListData modelWithJSON:@{@"datas":x[@"articleList"]}];
//            }
            
            @weakify(self);
            NSArray *viewModels = [data.datas.rac_sequence map:^CommonStwxItemViewModel *(ArticleListData* aListData)
            {
                @strongify(self);
                CommonStwxItemViewModel *itemViewModel = [[CommonStwxItemViewModel alloc] initWithData:aListData cellHeight:self.cellHeight];
                
                return itemViewModel;
            }].array;
            
            if (viewModels == nil || viewModels.count < pageSize)
            {
                self.lastPage = self.page;
                
                if (viewModels == nil)
                    viewModels = @[];
            }
            else
            {
                self.lastPage = 999;
            }
            
            if (self.shouldPullUpToLoadMore)
            {
                if (0 == pageIndex)
                {
                    self.dataSource = viewModels;
                }
                else
                {
                    if (self.dataSource == nil)
                    {
                        self.dataSource = viewModels;
                    }
                    else
                    {
                        self.dataSource = [self.dataSource arrayByAddingObjectsFromArray:viewModels];
                    }
                }
            }
            else
            {
                self.dataSource = viewModels;
            }
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
}

@end
